﻿
#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using UnityEditor;

using UnityEngine;
public class MashSave : EditorWindow
{
    public SelectionMode SelectionMode = SelectionMode.TopLevel;
    public MeshFilter[] Renderers;
    public string MeshPath = "Assets/0C1_Models/Test";

    [MenuItem("Window/MeshSave")]
    public static void Init()
    {
        EditorWindow.GetWindow<MashSave>().Show();
    }

    public void OnGUI()
    {
        GetSelectionMode();
        GetObject();
        GetMeshPath();
        DoSave();
    }

    private void GetSelectionMode()
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField(" Select model:", GUILayout.Width(100));
        SelectionMode = (SelectionMode)EditorGUILayout.EnumFlagsField(SelectionMode, GUILayout.Width(100));
        EditorGUILayout.EndHorizontal();
    }

    private void GetObject()
    {
        Renderers = Selection.GetFiltered<MeshFilter>(SelectionMode.TopLevel);

        EditorGUILayout.BeginVertical();
        EditorGUILayout.LabelField(" Objects to save mash:", GUILayout.Width(200));
        for (var i = 0; i < Renderers.Length; i++)
        {
            Renderers[i] = (MeshFilter)EditorGUILayout.ObjectField(Renderers[i], typeof(MeshFilter), true);
        }
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();
    }

    private void GetMeshPath()
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField(" Mesh save path:", GUILayout.Width(100));
        MeshPath = EditorGUILayout.TextField(MeshPath, GUILayout.Width(250));
        if (!MeshPath.EndsWith("/"))
            MeshPath += "/";
        EditorGUILayout.EndHorizontal();
    }

    private void DoSave()
    {
        if (GUILayout.Button("Save"))
        {
            foreach (var renderer in Renderers)
            {
                if (!string.IsNullOrWhiteSpace(AssetDatabase.GetAssetPath(renderer)))
                    continue;
                var file = MeshPath + renderer.sharedMesh.name + ".asset";
                AssetDatabase.CreateAsset(renderer.sharedMesh, file);
            }
        }
    }
}
#endif